import content
import huck
import huck.api.user.manage
import huck.ext.session_beaker
import huck.ext.user_pyrant
import pyrant
import string

class MainPage(huck.RequestHandler):

  def get(self):
    if self.user.is_authenticated():
      html = string.Template(content.main_page_logout_html).safe_substitute({ 'name': self.user.name(), 'logout_url': self.user.logout_url() })
    else:
      html = string.Template(content.main_page_login_html).safe_substitute({ 'login_url': self.user.login_url() })
    self.response.out.write(html)

class LoginPage(huck.RequestHandler):

  def get(self):
    if self.user.is_authenticated():
      self.redirect('/')
    else:
      html = string.Template(content.login_page_html).safe_substitute({ 'action': self.user.login_url() })
      self.response.out.write(html)

  def post(self):
    manage = huck.api.user.manage.get(self, self.user.type)
    if manage.login(email=self.request.get('email', ''), password=self.request.get('password', '')):
      self.redirect('/')
    else:
      self.redirect(self.user.login_url())

class LogoutPage(huck.RequestHandler):

  def get(self):
    manage = huck.api.user.manage.get(self, self.user.type)
    manage.logout()
    self.redirect('/')

class SignupPage(huck.RequestHandler):

  def get(self):
    if self.user.is_authenticated():
      self.redirect('/')
    else:
      self.response.out.write(content.signup_page_html)

  def post(self):
    name = self.request.get('name')
    email = self.request.get('email')
    password = self.request.get('password')
    if name and email and password:
      manage = huck.api.user.manage.get(self, self.user.type)
      manage.create(name=name, email=email, password=password)
      self.redirect('/')
    else:
      self.redirect('/signup')

# Setup application
url_mapping = [
               ('/', MainPage),
               ('/login', LoginPage),
               ('/logout', LogoutPage),
               ('/signup', SignupPage),
              ]
application = huck.Application(url_mapping, debug=True)

# Setup resources
huck.api.resource['pyrant'] = pyrant.Tyrant(host='example')

# Setup session
session = huck.ext.session_beaker.Create()
application = session.setup(application)

# Setup user
user = huck.ext.user_pyrant.Create(login_url='/login', logout_url='/logout', resource='pyrant')
application = user.setup(application)

if __name__ == '__main__':
  huck.run_dev('', 8080, application)
